from django.shortcuts import render
from django_redis import get_redis_connection
from drf_haystack.generics import HaystackGenericAPIView
from drf_haystack.mixins import FacetMixin
from drf_haystack.viewsets import HaystackViewSet
from rest_framework import status
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, CreateAPIView, ListCreateAPIView
from rest_framework.mixins import ListModelMixin
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from fjr.models import SKU
from fjr.serializers.search import LocationSerializer
from fjr.serializers.sku import SKUModelSerializer
from fjr.serializers.userbrowse import UserBrowseSerializer, UserBrowseListSerializer
from fjr.utils import StandardResultPagination


class SKUListAPIView(ListAPIView):
    queryset = SKU.objects.all()
    serializer_class = SKUModelSerializer
    pagination_class = StandardResultPagination
    # 排序设置
    filter_backends = [OrderingFilter]
    # 指定排序字段
    ordering_fields = ('id', 'comments', 'price')


class MySearchView(ListModelMixin, HaystackGenericAPIView):
    """搜索"""

    index_models = [SKU]
    serializer_class = LocationSerializer
    pagination_class = StandardResultPagination

    def get(self, request):
        return self.list(request)


class UserBrowseHistory(ModelViewSet):
    """用户浏览记录"""

    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.action == 'list':
            return UserBrowseListSerializer
        else:
            return UserBrowseSerializer

    def get_queryset(self):
        """获取用户浏览记录"""
        # 获取Redis存储的sku_id列表信息
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s' % self.request.user.id, 0, -1)
        skus = SKU.objects.filter(id__in=sku_ids)
        return skus

    def create(self, request, *args, **kwargs):
        request.data['user'] = self.request.user
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response(serializer.data, status=status.HTTP_201_CREATED,)


